import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SmartNotepad extends JFrame {
    private JTextArea textArea;
    private JTextPane markdownPreview;
    private JTree categoryTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel treeModel;
    private JTextField searchField;
    private JLabel titleLabel;
    private JLabel timeLabel;
    private JLabel categoryLabel;
    private JLabel wordCountLabel;
    private FileManager fileManager;
    private AIAssistant aiAssistant;
    private TextClassifier textClassifier;
    private NoteItem currentNote;
    private Map<String, List<NoteItem>> categorizedNotes;
    private List<String> categories;
    private JSplitPane rightSplitPane;
    private boolean isMarkdownMode = true; // 默认启用Markdown模式
    private boolean isEditMode = false; // 默认为预览模式
    private JButton editBtn; // 编辑内容按钮
    private JButton aiBtn; // AI助手按钮
    private JButton exportBtn; // 导出按钮
    private JButton saveBtn; // 保存按钮
    private JButton cancelBtn; // 取消编辑按钮

    // 现代化颜色方案
    private static final Color PRIMARY_COLOR = new Color(74, 144, 226);
    private static final Color BACKGROUND_COLOR = new Color(248, 249, 250);
    private static final Color SIDEBAR_COLOR = new Color(255, 255, 255);
    private static final Color TEXT_COLOR = new Color(33, 37, 41);
    private static final Color SECONDARY_TEXT_COLOR = new Color(108, 117, 125);
    private static final Color ACCENT_COLOR = new Color(40, 167, 69);
    private static final Color DANGER_COLOR = new Color(220, 53, 69);

    public SmartNotepad() {
        initializeData();
        initializeComponents();
        setupLayout();
        setupEventListeners();

        setTitle("智能记事本 - 学号:082340110 姓名:毕惜虹 独立开发");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1400, 900);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(1000, 700));

        // 加载数据并刷新界面
        refreshCategoryTree();

        // 如果没有笔记，显示欢迎信息
        if (categorizedNotes.values().stream().allMatch(List::isEmpty)) {
            titleLabel.setText("欢迎使用智能记事本");
            updateMarkdownPreview();
        }
    }

    private void initializeData() {
        fileManager = new FileManager();
        aiAssistant = new AIAssistant();
        textClassifier = new TextClassifier();

        // 从文件加载分类和笔记数据
        categories = fileManager.loadCategories();
        categorizedNotes = fileManager.loadNotes();

        // 确保所有分类都有对应的列表
        for (String category : categories) {
            categorizedNotes.computeIfAbsent(category, k -> new ArrayList<>());
        }
    }

    private void initializeComponents() {
        // 搜索框
        searchField = new JTextField();
        searchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                new EmptyBorder(8, 12, 8, 12)));
        searchField.setBackground(Color.WHITE);

        // 分类树
        rootNode = new DefaultMutableTreeNode("我的笔记");
        treeModel = new DefaultTreeModel(rootNode);
        categoryTree = new JTree(treeModel);
        categoryTree.setRootVisible(false);
        categoryTree.setShowsRootHandles(true);
        categoryTree.setCellRenderer(new CategoryTreeCellRenderer());
        categoryTree.setBackground(SIDEBAR_COLOR);
        categoryTree.setBorder(new EmptyBorder(10, 10, 10, 10));

        // 文本编辑区域
        textArea = new JTextArea();
        textArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setMargin(new Insets(30, 30, 30, 30));
        textArea.setBackground(Color.WHITE);
        textArea.setForeground(TEXT_COLOR);
        textArea.setCaretColor(PRIMARY_COLOR);
        textArea.setSelectionColor(
                new Color(PRIMARY_COLOR.getRed(), PRIMARY_COLOR.getGreen(), PRIMARY_COLOR.getBlue(), 50));
        textArea.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // Markdown预览区域
        markdownPreview = new JTextPane();
        markdownPreview.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        markdownPreview.setMargin(new Insets(30, 30, 30, 30));
        markdownPreview.setBackground(Color.WHITE);
        markdownPreview.setForeground(TEXT_COLOR);
        markdownPreview.setEditable(false);
        markdownPreview.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题和信息标签
        titleLabel = new JLabel("新建笔记");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        titleLabel.setForeground(TEXT_COLOR);

        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        timeLabel.setForeground(SECONDARY_TEXT_COLOR);

        categoryLabel = new JLabel("分类: 未分类");
        categoryLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        categoryLabel.setForeground(SECONDARY_TEXT_COLOR);

        wordCountLabel = new JLabel("0 字");
        wordCountLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        wordCountLabel.setForeground(SECONDARY_TEXT_COLOR);
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 左侧面板
        JPanel leftPanel = createLeftPanel();

        // 右侧面板
        JPanel rightPanel = createRightPanel();

        // 分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        splitPane.setDividerLocation(350);
        splitPane.setDividerSize(1);
        splitPane.setBorder(null);
        splitPane.setResizeWeight(0.0);

        add(splitPane, BorderLayout.CENTER);
    }

    private JPanel createLeftPanel() {
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBackground(SIDEBAR_COLOR);
        leftPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, new Color(230, 230, 230)));

        // 顶部：仅标题
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setBackground(SIDEBAR_COLOR);
        headerPanel.setBorder(new EmptyBorder(15, 15, 10, 15));

        JLabel titleLabel = new JLabel("我的笔记");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);

        headerPanel.add(titleLabel, BorderLayout.WEST);

        // 搜索框面板
        JPanel searchPanel = new JPanel(new BorderLayout());
        searchPanel.setBackground(SIDEBAR_COLOR);
        searchPanel.setBorder(new EmptyBorder(0, 15, 10, 15));
        searchPanel.add(searchField, BorderLayout.CENTER);

        // 操作按钮面板 - 重新排列按钮顺序
        JPanel operationPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 5));
        operationPanel.setBackground(SIDEBAR_COLOR);
        operationPanel.setBorder(new EmptyBorder(0, 10, 10, 10));

        JButton newCategoryBtn = createModernButton("新建分类", ACCENT_COLOR, Color.WHITE);
        newCategoryBtn.addActionListener(e -> createNewCategory());

        JButton smartClassifyBtn = createModernButton("智能分类", new Color(255, 193, 7), Color.WHITE);
        smartClassifyBtn.addActionListener(e -> autoClassifyAllNotes());

        JButton newNoteBtn = createModernButton("+ 新建笔记", PRIMARY_COLOR, Color.WHITE);
        newNoteBtn.addActionListener(e -> createNewNote());

        operationPanel.add(newCategoryBtn);
        operationPanel.add(smartClassifyBtn);
        operationPanel.add(newNoteBtn);

        // 分类树滚动面板
        JScrollPane treeScrollPane = new JScrollPane(categoryTree);
        treeScrollPane.setBorder(null);
        treeScrollPane.setBackground(SIDEBAR_COLOR);
        treeScrollPane.getViewport().setBackground(SIDEBAR_COLOR);

        // 版权信息
        JPanel copyrightPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        copyrightPanel.setBackground(SIDEBAR_COLOR);
        copyrightPanel.setBorder(new EmptyBorder(10, 15, 15, 15));

        JLabel copyrightLabel = new JLabel("学号:082340110 姓名:毕惜虹 独立开发");
        copyrightLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
        copyrightLabel.setForeground(SECONDARY_TEXT_COLOR);

        copyrightPanel.add(copyrightLabel);

        leftPanel.add(headerPanel, BorderLayout.NORTH);

        // 中央面板布局修改：让分类树占据主要空间
        JPanel topCenterPanel = new JPanel(new BorderLayout());
        topCenterPanel.add(searchPanel, BorderLayout.NORTH);
        topCenterPanel.add(operationPanel, BorderLayout.SOUTH);

        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(topCenterPanel, BorderLayout.NORTH);
        centerPanel.add(treeScrollPane, BorderLayout.CENTER); // 改为CENTER，让树占据主要空间

        leftPanel.add(centerPanel, BorderLayout.CENTER);
        leftPanel.add(copyrightPanel, BorderLayout.SOUTH);

        return leftPanel;
    }

    private JPanel createRightPanel() {
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setBackground(Color.WHITE);

        // 信息栏（包含标题、时间等信息）
        JPanel infoPanel = createInfoPanel();

        // 按钮面板（放在信息栏下方）
        JPanel buttonPanel = createButtonPanel();

        // 顶部面板（信息栏 + 按钮面板）
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(infoPanel, BorderLayout.NORTH);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 内容区域（默认只显示预览）
        JScrollPane previewScrollPane = new JScrollPane(markdownPreview);
        previewScrollPane.setBorder(null);
        previewScrollPane.setBackground(Color.WHITE);
        previewScrollPane.getViewport().setBackground(Color.WHITE);

        rightPanel.add(topPanel, BorderLayout.NORTH);
        rightPanel.add(previewScrollPane, BorderLayout.CENTER); // 内容区域占据中央主要空间

        return rightPanel;
    }

    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 10));
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 1, 0, new Color(230, 230, 230)),
                new EmptyBorder(10, 20, 10, 20))); // 增加内边距

        // 编辑内容按钮
        editBtn = createModernButton("编辑内容", PRIMARY_COLOR, Color.WHITE);
        editBtn.addActionListener(e -> toggleEditMode());

        // 取消编辑按钮
        cancelBtn = createModernButton("取消", SECONDARY_TEXT_COLOR, Color.WHITE);
        cancelBtn.addActionListener(e -> cancelEdit());

        aiBtn = createModernButton("AI助手", ACCENT_COLOR, Color.WHITE);
        aiBtn.addActionListener(e -> showAIAssistant());

        exportBtn = createModernButton("导出", SECONDARY_TEXT_COLOR, Color.WHITE);
        exportBtn.addActionListener(e -> exportNote());

        saveBtn = createModernButton("保存", PRIMARY_COLOR, Color.WHITE);
        saveBtn.addActionListener(e -> saveCurrentNote());

        // 初始状态：只显示编辑内容按钮
        buttonPanel.add(editBtn);

        return buttonPanel;
    }

    private JPanel createInfoPanel() {
        JPanel infoPanel = new JPanel(new BorderLayout());
        infoPanel.setBackground(Color.WHITE);
        infoPanel.setBorder(new EmptyBorder(20, 20, 10, 20));

        // 左侧 - 标题和时间
        JPanel leftInfo = new JPanel();
        leftInfo.setLayout(new BoxLayout(leftInfo, BoxLayout.Y_AXIS));
        leftInfo.setBackground(Color.WHITE);

        leftInfo.add(titleLabel);
        leftInfo.add(Box.createVerticalStrut(5));
        leftInfo.add(timeLabel);

        // 右侧 - 分类和字数
        JPanel rightInfo = new JPanel();
        rightInfo.setLayout(new BoxLayout(rightInfo, BoxLayout.Y_AXIS));
        rightInfo.setBackground(Color.WHITE);

        JPanel categoryPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        categoryPanel.setBackground(Color.WHITE);
        categoryPanel.add(categoryLabel);

        JPanel wordPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        wordPanel.setBackground(Color.WHITE);
        wordPanel.add(wordCountLabel);

        rightInfo.add(categoryPanel);
        rightInfo.add(Box.createVerticalStrut(5));
        rightInfo.add(wordPanel);

        infoPanel.add(leftInfo, BorderLayout.WEST);
        infoPanel.add(rightInfo, BorderLayout.EAST);

        return infoPanel;
    }

    private JButton createModernButton(String text, Color bgColor, Color textColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        button.setBackground(bgColor);
        button.setForeground(textColor);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setBorder(new EmptyBorder(8, 16, 8, 16));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        Color originalColor = bgColor;
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(originalColor.darker());
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(originalColor);
            }
        });

        return button;
    }

    private void setupEventListeners() {
        // 搜索框实时搜索
        searchField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                performSearch();
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                performSearch();
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                performSearch();
            }
        });

        // 分类树选择事件
        categoryTree.addTreeSelectionListener(e -> {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree.getLastSelectedPathComponent();
            if (selectedNode != null && selectedNode.getUserObject() instanceof NoteItem) {
                loadNote((NoteItem) selectedNode.getUserObject());
            }
        });

        // 添加右键菜单支持
        categoryTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showContextMenu(e);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showContextMenu(e);
                }
            }
        });

        // 文本变化监听
        textArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                updateWordCount();
                updateCurrentNoteContent();
                if (isMarkdownMode)
                    updateMarkdownPreview();
            }

            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                updateWordCount();
                updateCurrentNoteContent();
                if (isMarkdownMode)
                    updateMarkdownPreview();
            }

            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                updateWordCount();
                updateCurrentNoteContent();
                if (isMarkdownMode)
                    updateMarkdownPreview();
            }
        });
    }

    private void createNewNote() {
        String category = "未分类";
        if (currentNote != null) {
            category = currentNote.category;
        }

        NoteItem newNote = new NoteItem();
        newNote.title = "新建笔记";
        newNote.content = "";
        newNote.createTime = LocalDateTime.now();
        newNote.modifyTime = LocalDateTime.now();
        newNote.category = category;

        categorizedNotes.get(category).add(0, newNote);
        refreshCategoryTree();
        loadNote(newNote);
        saveDataToFile(); // 自动保存
        textArea.requestFocus();
    }

    private void createNewCategory() {
        String categoryName = JOptionPane.showInputDialog(this, "请输入新分类名称:", "新建分类", JOptionPane.PLAIN_MESSAGE);
        if (categoryName != null && !categoryName.trim().isEmpty()) {
            categoryName = categoryName.trim();
            if (!categories.contains(categoryName)) {
                categories.add(categoryName);
                categorizedNotes.put(categoryName, new ArrayList<>());
                refreshCategoryTree();
                saveDataToFile(); // 自动保存
                JOptionPane.showMessageDialog(this, "分类 \"" + categoryName + "\" 创建成功！", "提示",
                        JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "分类 \"" + categoryName + "\" 已存在！", "提示",
                        JOptionPane.WARNING_MESSAGE);
            }
        }
    }

    private void autoClassifyAllNotes() {
        int totalNotes = 0;
        int classifiedNotes = 0;

        // 显示开始分类的消息
        JOptionPane.showMessageDialog(this, "开始智能分类，请稍候...", "智能分类", JOptionPane.INFORMATION_MESSAGE);

        for (String category : categories) {
            List<NoteItem> notes = categorizedNotes.get(category);
            if (notes != null) {
                for (NoteItem note : new ArrayList<>(notes)) {
                    totalNotes++;
                    if (!note.content.trim().isEmpty()) {
                        try {
                            String newCategory = textClassifier.classify(note.content);
                            if (!newCategory.equals(note.category)) {
                                // 移动到新分类
                                notes.remove(note);
                                note.category = newCategory;
                                note.modifyTime = LocalDateTime.now();
                                categorizedNotes.get(newCategory).add(note);
                                classifiedNotes++;
                            }
                        } catch (Exception e) {
                            System.err.println("分类笔记时出错: " + note.title + " - " + e.getMessage());
                        }
                    }
                }
            }
        }

        refreshCategoryTree();

        String message;
        if (totalNotes == 0) {
            message = "没有找到可分类的笔记。";
        } else if (classifiedNotes == 0) {
            message = "智能分类完成！\n共检查了 " + totalNotes + " 个笔记，所有笔记分类都合适，无需调整。";
        } else {
            message = "智能分类完成！\n共处理 " + totalNotes + " 个笔记，重新分类 " + classifiedNotes + " 个笔记。";
            saveDataToFile(); // 有分类变更时自动保存
        }

        JOptionPane.showMessageDialog(this, message, "分类结果", JOptionPane.INFORMATION_MESSAGE);
    }

    private void toggleMarkdownMode() {
        isMarkdownMode = !isMarkdownMode;

        if (isMarkdownMode) {
            // 启用Markdown预览，显示分屏
            rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    new JScrollPane(textArea), new JScrollPane(markdownPreview));
            rightSplitPane.setDividerLocation(0.5);
            rightSplitPane.setResizeWeight(0.5);
            rightSplitPane.setBorder(null);

            // 更新右侧面板
            Container parent = textArea.getParent().getParent().getParent();
            if (parent instanceof JPanel) {
                JPanel rightPanel = (JPanel) parent;
                rightPanel.removeAll();
                rightPanel.add(createButtonPanel(), BorderLayout.NORTH);
                rightPanel.add(createInfoPanel(), BorderLayout.CENTER);
                rightPanel.add(rightSplitPane, BorderLayout.SOUTH);
                rightPanel.revalidate();
                rightPanel.repaint();
            }

            updateMarkdownPreview();
        } else {
            // 禁用Markdown预览，只显示编辑区
            JScrollPane editScrollPane = new JScrollPane(textArea);
            editScrollPane.setBorder(null);
            editScrollPane.setBackground(Color.WHITE);
            editScrollPane.getViewport().setBackground(Color.WHITE);

            Container parent = textArea.getParent().getParent().getParent();
            if (parent instanceof JPanel) {
                JPanel rightPanel = (JPanel) parent;
                rightPanel.removeAll();
                rightPanel.add(createButtonPanel(), BorderLayout.NORTH);
                rightPanel.add(createInfoPanel(), BorderLayout.CENTER);
                rightPanel.add(editScrollPane, BorderLayout.SOUTH);
                rightPanel.revalidate();
                rightPanel.repaint();
            }
        }
    }

    private void toggleEditMode() {
        isEditMode = !isEditMode;
        updateContentArea();
        updateButtonPanel();
    }

    private void cancelEdit() {
        isEditMode = false;
        // 重新加载当前笔记内容，放弃未保存的修改
        if (currentNote != null) {
            textArea.setText(currentNote.content);
            updateMarkdownPreview();
        }
        updateContentArea();
        updateButtonPanel();
    }

    private void updateContentArea() {
        // 获取右侧面板
        Container parent = (markdownPreview.getParent() != null) ? markdownPreview.getParent().getParent().getParent()
                : null;

        if (parent == null && textArea.getParent() != null) {
            parent = textArea.getParent().getParent().getParent();
        }

        if (parent instanceof JPanel) {
            JPanel rightPanel = (JPanel) parent;

            // 找到并移除内容区域组件（CENTER位置的组件）
            Component centerComponent = null;
            BorderLayout layout = (BorderLayout) rightPanel.getLayout();
            for (Component comp : rightPanel.getComponents()) {
                Object constraint = layout.getConstraints(comp);
                if (BorderLayout.CENTER.equals(constraint)) {
                    centerComponent = comp;
                    break;
                }
            }

            if (centerComponent != null) {
                rightPanel.remove(centerComponent);
            }

            if (isEditMode) {
                // 编辑模式：显示编辑区域
                JScrollPane editScrollPane = new JScrollPane(textArea);
                editScrollPane.setBorder(null);
                editScrollPane.setBackground(Color.WHITE);
                editScrollPane.getViewport().setBackground(Color.WHITE);
                rightPanel.add(editScrollPane, BorderLayout.CENTER);
            } else {
                // 预览模式：显示预览区域
                JScrollPane previewScrollPane = new JScrollPane(markdownPreview);
                previewScrollPane.setBorder(null);
                previewScrollPane.setBackground(Color.WHITE);
                previewScrollPane.getViewport().setBackground(Color.WHITE);
                rightPanel.add(previewScrollPane, BorderLayout.CENTER);
                updateMarkdownPreview();
            }

            rightPanel.revalidate();
            rightPanel.repaint();
        }
    }

    private void showAIAssistant() {
        AIAssistantDialog dialog = new AIAssistantDialog(this, aiAssistant);
        dialog.setVisible(true);

        String result = dialog.getResult();
        if (result != null && !result.trim().isEmpty()) {
            if (textArea.getSelectedText() != null) {
                textArea.replaceSelection(result);
            } else {
                textArea.append(result);
            }
        }
    }

    private void exportNote() {
        if (currentNote == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个笔记", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("文本文件 (*.txt)", "txt"));
        fileChooser.setSelectedFile(new File(currentNote.title + ".txt"));

        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            if (!file.getName().toLowerCase().endsWith(".txt")) {
                file = new File(file.getAbsolutePath() + ".txt");
            }

            if (fileManager.writeFile(file, currentNote.content)) {
                JOptionPane.showMessageDialog(this, "导出成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "导出失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void saveCurrentNote() {
        if (currentNote != null) {
            currentNote.modifyTime = LocalDateTime.now();
            refreshCategoryTree();
            saveDataToFile(); // 自动保存
            JOptionPane.showMessageDialog(this, "笔记已保存", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void performSearch() {
        String searchTerm = searchField.getText().trim().toLowerCase();

        if (searchTerm.isEmpty()) {
            refreshCategoryTree();
            return;
        }

        // 重新构建树，只显示匹配的笔记
        rootNode.removeAllChildren();

        for (String category : categories) {
            DefaultMutableTreeNode categoryNode = new DefaultMutableTreeNode(category);
            List<NoteItem> notes = categorizedNotes.get(category);
            boolean hasMatchingNotes = false;

            if (notes != null) {
                for (NoteItem note : notes) {
                    if (note.title.toLowerCase().contains(searchTerm) ||
                            note.content.toLowerCase().contains(searchTerm) ||
                            note.category.toLowerCase().contains(searchTerm)) {
                        DefaultMutableTreeNode noteNode = new DefaultMutableTreeNode(note);
                        categoryNode.add(noteNode);
                        hasMatchingNotes = true;
                    }
                }
            }

            if (hasMatchingNotes) {
                rootNode.add(categoryNode);
            }
        }

        treeModel.reload();
        // 展开所有分类
        for (int i = 0; i < categoryTree.getRowCount(); i++) {
            categoryTree.expandRow(i);
        }
    }

    private void loadNote(NoteItem note) {
        currentNote = note;

        textArea.setText(note.content);
        titleLabel.setText(note.title);
        timeLabel.setText("创建于 " + note.createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        categoryLabel.setText("分类: " + note.category);
        updateWordCount();

        // 强制进入预览模式
        isEditMode = false;
        updateMarkdownPreview();
        updateContentArea();
        updateButtonPanel();

        textArea.setCaretPosition(0);
    }

    private void updateWordCount() {
        String text = textArea.getText();
        int wordCount = text.trim().isEmpty() ? 0 : text.length();
        wordCountLabel.setText(wordCount + " 字");
    }

    private void updateCurrentNoteContent() {
        if (currentNote != null) {
            currentNote.content = textArea.getText();
            currentNote.modifyTime = LocalDateTime.now();

            // 自动生成标题
            String content = textArea.getText().trim();
            if (!content.isEmpty()) {
                String autoTitle = content.length() > 20 ? content.substring(0, 20) + "..." : content;
                currentNote.title = autoTitle.replace("\n", " ");
                titleLabel.setText(currentNote.title);
            }
        }
    }

    private void updateMarkdownPreview() {
        String markdownText = (currentNote != null) ? currentNote.content : textArea.getText();
        String htmlText = convertMarkdownToHtml(markdownText);
        markdownPreview.setContentType("text/html");
        markdownPreview.setText(htmlText);
        markdownPreview.setCaretPosition(0);
    }

    private String convertMarkdownToHtml(String markdown) {
        if (markdown == null || markdown.trim().isEmpty()) {
            return "<html><body style='font-family: Microsoft YaHei; padding: 20px;'></body></html>";
        }

        StringBuilder html = new StringBuilder();
        html.append("<html><head>");
        html.append("<style>");
        html.append(
                "body { font-family: 'Microsoft YaHei', sans-serif; line-height: 1.6; color: #333; padding: 20px; }");
        html.append("h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }");
        html.append("h2 { color: #34495e; border-bottom: 1px solid #bdc3c7; padding-bottom: 5px; }");
        html.append("h3 { color: #7f8c8d; }");
        html.append("p { margin: 10px 0; }");
        html.append("ul, ol { margin: 10px 0; padding-left: 30px; }");
        html.append("li { margin: 5px 0; }");
        html.append("strong { color: #e74c3c; }");
        html.append("em { color: #9b59b6; }");
        html.append(
                "code { background-color: #f8f9fa; padding: 2px 5px; border-radius: 3px; font-family: 'Consolas', monospace; }");
        html.append(
                "blockquote { border-left: 4px solid #3498db; margin: 15px 0; padding: 10px 15px; background-color: #f8f9fa; }");
        html.append("</style>");
        html.append("</head><body>");

        String[] lines = markdown.split("\\n");
        boolean inList = false;
        boolean inOrderedList = false;

        for (String line : lines) {
            line = line.trim();

            if (line.isEmpty()) {
                html.append("<br/>");
                continue;
            }

            // 标题处理
            if (line.startsWith("# ")) {
                html.append("<h1>").append(processInlineMarkdown(line.substring(2))).append("</h1>");
            } else if (line.startsWith("## ")) {
                html.append("<h2>").append(processInlineMarkdown(line.substring(3))).append("</h2>");
            } else if (line.startsWith("### ")) {
                html.append("<h3>").append(processInlineMarkdown(line.substring(4))).append("</h3>");
            }
            // 无序列表
            else if (line.startsWith("- ") || line.startsWith("* ")) {
                if (!inList) {
                    html.append("<ul>");
                    inList = true;
                }
                if (inOrderedList) {
                    html.append("</ol>");
                    inOrderedList = false;
                }
                html.append("<li>").append(processInlineMarkdown(line.substring(2))).append("</li>");
            }
            // 有序列表
            else if (line.matches("^\\d+\\. .*")) {
                if (!inOrderedList) {
                    html.append("<ol>");
                    inOrderedList = true;
                }
                if (inList) {
                    html.append("</ul>");
                    inList = false;
                }
                String content = line.substring(line.indexOf(". ") + 2);
                html.append("<li>").append(processInlineMarkdown(content)).append("</li>");
            }
            // 引用
            else if (line.startsWith("> ")) {
                if (inList) {
                    html.append("</ul>");
                    inList = false;
                }
                if (inOrderedList) {
                    html.append("</ol>");
                    inOrderedList = false;
                }
                html.append("<blockquote>").append(processInlineMarkdown(line.substring(2))).append("</blockquote>");
            }
            // 普通段落
            else {
                if (inList) {
                    html.append("</ul>");
                    inList = false;
                }
                if (inOrderedList) {
                    html.append("</ol>");
                    inOrderedList = false;
                }
                html.append("<p>").append(processInlineMarkdown(line)).append("</p>");
            }
        }

        // 关闭未关闭的列表
        if (inList) {
            html.append("</ul>");
        }
        if (inOrderedList) {
            html.append("</ol>");
        }

        html.append("</body></html>");
        return html.toString();
    }

    private String processInlineMarkdown(String text) {
        // 处理粗体 **text** 或 __text__
        text = text.replaceAll("\\*\\*(.*?)\\*\\*", "<strong>$1</strong>");
        text = text.replaceAll("__(.*?)__", "<strong>$1</strong>");

        // 处理斜体 *text* 或 _text_
        text = text.replaceAll("\\*(.*?)\\*", "<em>$1</em>");
        text = text.replaceAll("_(.*?)_", "<em>$1</em>");

        // 处理行内代码 `code`
        text = text.replaceAll("`(.*?)`", "<code>$1</code>");

        return text;
    }

    // 现代化树渲染器
    private class CategoryTreeCellRenderer implements TreeCellRenderer {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

            if (node.getUserObject() instanceof NoteItem) {
                // 笔记项 - 现代化卡片设计
                NoteItem note = (NoteItem) node.getUserObject();
                return createModernNoteCard(note, selected);
            } else {
                // 分类项 - 现代化分类标题
                String categoryName = node.getUserObject().toString();
                return createModernCategoryHeader(categoryName, node.getChildCount(), expanded, selected);
            }
        }

        private JPanel createModernCategoryHeader(String categoryName, int noteCount, boolean expanded,
                boolean selected) {
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBackground(
                    selected ? new Color(PRIMARY_COLOR.getRed(), PRIMARY_COLOR.getGreen(), PRIMARY_COLOR.getBlue(), 30)
                            : SIDEBAR_COLOR);
            panel.setBorder(new EmptyBorder(8, 15, 8, 15));

            // 分类名称
            JLabel nameLabel = new JLabel(categoryName);
            nameLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
            nameLabel.setForeground(TEXT_COLOR);

            // 右侧信息面板：笔记数量和当前时间
            JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
            rightPanel.setBackground(panel.getBackground());

            JLabel countLabel = new JLabel("(" + noteCount + ")");
            countLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
            countLabel.setForeground(SECONDARY_TEXT_COLOR);

            JLabel timeLabel = new JLabel(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
            timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
            timeLabel.setForeground(SECONDARY_TEXT_COLOR);

            rightPanel.add(countLabel);
            rightPanel.add(timeLabel);

            panel.add(nameLabel, BorderLayout.WEST);
            panel.add(rightPanel, BorderLayout.EAST);

            return panel;
        }

        private JPanel createModernNoteCard(NoteItem note, boolean selected) {
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.setBorder(new EmptyBorder(4, 25, 4, 15)); // 进一步减少边距

            // 根据选择状态设置背景色
            Color bgColor = selected
                    ? new Color(PRIMARY_COLOR.getRed(), PRIMARY_COLOR.getGreen(), PRIMARY_COLOR.getBlue(), 40)
                    : SIDEBAR_COLOR;
            panel.setBackground(bgColor);

            // 鼠标悬停效果
            panel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    if (!selected) {
                        panel.setBackground(new Color(248, 249, 250));
                    }
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    if (!selected) {
                        panel.setBackground(SIDEBAR_COLOR);
                    }
                }
            });

            // 标题
            JLabel titleLabel = new JLabel(note.title);
            titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));
            titleLabel.setForeground(TEXT_COLOR);
            titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

            // 内容预览
            String preview = note.content.length() > 25 ? note.content.substring(0, 25).replace("\n", " ") + "..."
                    : note.content.replace("\n", " ");
            if (preview.trim().isEmpty()) {
                preview = "暂无内容";
            }
            JLabel previewLabel = new JLabel(preview);
            previewLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
            previewLabel.setForeground(SECONDARY_TEXT_COLOR);
            previewLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

            // 底部信息面板：分类标签在左，时间在右
            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.setBackground(bgColor);
            bottomPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            bottomPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));

            // 分类标签
            JLabel categoryTag = new JLabel(note.category);
            categoryTag.setFont(new Font("Microsoft YaHei", Font.PLAIN, 8));
            categoryTag.setForeground(Color.WHITE);
            categoryTag.setBackground(PRIMARY_COLOR);
            categoryTag.setOpaque(true);
            categoryTag.setBorder(new EmptyBorder(1, 3, 1, 3));

            // 时间标签
            JLabel timeLabel = new JLabel(note.modifyTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")));
            timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 8));
            timeLabel.setForeground(SECONDARY_TEXT_COLOR);

            bottomPanel.add(categoryTag, BorderLayout.WEST);
            bottomPanel.add(timeLabel, BorderLayout.EAST);

            // 添加所有组件
            panel.add(titleLabel);
            panel.add(Box.createVerticalStrut(1));
            panel.add(previewLabel);
            panel.add(Box.createVerticalStrut(2));
            panel.add(bottomPanel);

            return panel;
        }
    }

    private void refreshCategoryTree() {
        rootNode.removeAllChildren();

        for (String category : categories) {
            DefaultMutableTreeNode categoryNode = new DefaultMutableTreeNode(category);
            List<NoteItem> notes = categorizedNotes.get(category);

            if (notes != null) {
                for (NoteItem note : notes) {
                    DefaultMutableTreeNode noteNode = new DefaultMutableTreeNode(note);
                    categoryNode.add(noteNode);
                }
            }

            rootNode.add(categoryNode);
        }

        treeModel.reload();
        for (int i = 0; i < categoryTree.getRowCount(); i++) {
            categoryTree.expandRow(i);
        }
    }

    // 显示右键菜单
    private void showContextMenu(MouseEvent e) {
        TreePath path = categoryTree.getPathForLocation(e.getX(), e.getY());
        if (path != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node.getUserObject() instanceof NoteItem) {
                NoteItem note = (NoteItem) node.getUserObject();
                categoryTree.setSelectionPath(path); // 选中右键点击的项
                showNoteContextMenu(e, note);
            }
        }
    }

    // 显示笔记右键菜单
    private void showNoteContextMenu(MouseEvent e, NoteItem note) {
        JPopupMenu popupMenu = new JPopupMenu();

        // 编辑标题
        JMenuItem editTitleItem = new JMenuItem("编辑标题");
        editTitleItem.addActionListener(evt -> showEditTitleDialog(note));
        popupMenu.add(editTitleItem);

        // 修改分类
        JMenuItem changeCategoryItem = new JMenuItem("修改分类");
        changeCategoryItem.addActionListener(evt -> showChangeCategoryDialog(note));
        popupMenu.add(changeCategoryItem);

        popupMenu.addSeparator();

        // 删除笔记
        JMenuItem deleteItem = new JMenuItem("删除笔记");
        deleteItem.setForeground(DANGER_COLOR);
        deleteItem.addActionListener(evt -> showDeleteNoteDialog(note));
        popupMenu.add(deleteItem);

        popupMenu.show(categoryTree, e.getX(), e.getY());
    }

    // 显示编辑标题对话框
    private void showEditTitleDialog(NoteItem note) {
        String newTitle = JOptionPane.showInputDialog(this,
                "请输入新的标题:",
                "编辑标题",
                JOptionPane.PLAIN_MESSAGE);

        if (newTitle != null && !newTitle.trim().isEmpty()) {
            note.title = newTitle.trim();
            note.modifyTime = LocalDateTime.now();
            refreshCategoryTree();
            saveDataToFile(); // 自动保存
            if (currentNote == note) {
                titleLabel.setText(note.title);
            }
        }
    }

    // 显示修改分类对话框
    private void showChangeCategoryDialog(NoteItem note) {
        String[] categoryArray = categories.toArray(new String[0]);
        String newCategory = (String) JOptionPane.showInputDialog(this,
                "请选择新的分类:",
                "修改分类",
                JOptionPane.PLAIN_MESSAGE,
                null,
                categoryArray,
                note.category);

        if (newCategory != null && !newCategory.equals(note.category)) {
            // 从原分类中移除
            List<NoteItem> oldCategoryNotes = categorizedNotes.get(note.category);
            if (oldCategoryNotes != null) {
                oldCategoryNotes.remove(note);
            }

            // 添加到新分类
            note.category = newCategory;
            note.modifyTime = LocalDateTime.now();
            categorizedNotes.get(newCategory).add(note);

            refreshCategoryTree();
            saveDataToFile(); // 自动保存
            if (currentNote == note) {
                categoryLabel.setText("分类: " + note.category);
            }
        }
    }

    // 显示删除笔记确认对话框
    private void showDeleteNoteDialog(NoteItem note) {
        int result = JOptionPane.showConfirmDialog(this,
                "确定要删除笔记 \"" + note.title + "\" 吗？\n此操作无法撤销。",
                "确认删除",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE);

        if (result == JOptionPane.YES_OPTION) {
            List<NoteItem> categoryNotes = categorizedNotes.get(note.category);
            if (categoryNotes != null) {
                categoryNotes.remove(note);
            }
            refreshCategoryTree();
            saveDataToFile(); // 自动保存
            if (currentNote == note) {
                currentNote = null;
                textArea.setText("");
                titleLabel.setText("请选择笔记");
                updateMarkdownPreview();
            }
        }
    }

    private void updateButtonPanel() {
        // 直接获取按钮面板并更新按钮
        SwingUtilities.invokeLater(() -> {
            Container container = getContentPane();
            JPanel buttonPanel = findButtonPanel(container);

            if (buttonPanel != null) {
                buttonPanel.removeAll();

                if (isEditMode) {
                    // 编辑模式：显示AI助手、导出、保存、取消按钮
                    buttonPanel.add(aiBtn);
                    buttonPanel.add(exportBtn);
                    buttonPanel.add(saveBtn);
                    buttonPanel.add(cancelBtn);
                } else {
                    // 预览模式：只显示编辑内容按钮
                    buttonPanel.add(editBtn);
                }

                buttonPanel.revalidate();
                buttonPanel.repaint();
            }
        });
    }

    // 递归查找按钮面板
    private JPanel findButtonPanel(Container container) {
        if (container instanceof JPanel) {
            JPanel panel = (JPanel) container;
            if (panel.getLayout() instanceof FlowLayout) {
                // 检查是否包含我们的按钮
                for (Component comp : panel.getComponents()) {
                    if (comp == editBtn || comp == aiBtn || comp == saveBtn || comp == exportBtn || comp == cancelBtn) {
                        return panel;
                    }
                }
            }
        }

        // 递归搜索子组件
        for (Component comp : container.getComponents()) {
            if (comp instanceof Container) {
                JPanel found = findButtonPanel((Container) comp);
                if (found != null) {
                    return found;
                }
            }
        }

        return null;
    }

    // 保存数据到文件
    private void saveDataToFile() {
        SwingUtilities.invokeLater(() -> {
            try {
                fileManager.saveNotes(categorizedNotes);
                fileManager.saveCategories(categories);
            } catch (Exception e) {
                System.err.println("保存数据失败: " + e.getMessage());
            }
        });
    }

    public static class NoteItem {
        String title;
        String content;
        LocalDateTime createTime;
        LocalDateTime modifyTime;
        String category;

        @Override
        public String toString() {
            return title;
        }
    }
}